package com.ys.controller;

import com.ys.config.Config;
import com.ys.dao.UserMapper;
import com.ys.entity.User;
import com.ys.service.AsyncService;
import com.ys.service.UserService;
import com.ys.utils.ConvertHandler;
import com.ys.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * @ClassName UserController
 * @Author 1628994918qq.com
 * @Date 2023/3/27 9:58
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private AsyncService asyncService;

    @Autowired
    private UserMapper userMapper;


    @RequestMapping("/insertUser")
    public R insertUser() {
        R r = new R();
        List<User> userList = new ArrayList<>();
        for (int i = 0; i < 300000; i++) {
            User user = new User();
            //user.setId(i);
            user.setUserName("第" + i + "条用户数据");
            user.setPassWord(Base64.getEncoder().encodeToString(("12dd4@" + i).getBytes()));
            userList.add(user);
        }

        log.info("=======开始插入数据=======");
        long startTime = System.currentTimeMillis();

        //消耗时间23138毫秒
        boolean b = userService.insertUser(userList);

        //消耗64095毫秒
        //boolean b1 = userService.saveBatch(userList);

        long spendTime = System.currentTimeMillis() - startTime;
        log.info("批量插入消耗时间：[{}]", spendTime);
        r.setCode(200);
        r.setMsg("插入数据成功");
        r.setData(b);
        r.setTime(spendTime);
        return r;
    }

    /**
     * 测试线程池
     */
    @Async("myExecutor")
    @RequestMapping("/test")
    public void test() {
        System.out.println("===" + Thread.currentThread().getName());
        System.out.println("===" + Thread.currentThread().getName());
        System.out.println("===" + Thread.currentThread().getName());
    }

    /**
     * 使用多线程批量插入30万条数据  每个线程1000条数据15496毫秒
     * @return
     */
    @Async("myExecutor")
    @RequestMapping("/insertUser1")
    public R insertUser1() {
        R r = new R();
        List<User> userList = new ArrayList<>();
        for (int i = 0; i < 300000; i++) {
            User user = new User();
            user.setId(i);
            user.setUserName("第" + i + "条用户数据");
            user.setPassWord(Base64.getEncoder().encodeToString(("12dd4@" + i).getBytes()));
            userList.add(user);
        }

        log.info("=======开始插入数据=======");

        //测试每100条数据插入开一个线程
        List<List<User>> lists = ConvertHandler.splitList(userList, 500);
        CountDownLatch countDownLatch = new CountDownLatch(lists.size());
        long startTime = System.currentTimeMillis();
        for (List<User> listSub : lists) {
            asyncService.executeAsync(listSub, userMapper, countDownLatch);
        }

        try {
            countDownLatch.await(); //保证之前的所有的线程都执行完成，才会走下面的；
            // 这样就可以在下面拿到所有线程执行完的集合结果
        } catch (Exception e) {
            log.error("阻塞异常:" + e.getMessage());
            r.setCode(500);
            r.setMsg("插入失败");
            return r;
        }
        long spendTime = System.currentTimeMillis() - startTime;
        System.out.println("多线程批量插入30万条数据消耗时间：" + spendTime + "毫秒");
        r.setCode(200);
        r.setMsg("插入数据成功");
        r.setTime(spendTime);
        return r;
    }
}
